<template>
  <CollapsibleSection title="是否收案" :is-expanded="isExpanded" @toggle="$emit('toggle')">
    <div class="form-container">
      <p class="tip">收案流程管理，请按照流程完成收案信息登记</p>

      <!-- 流程步骤指示器 -->
      <div class="process-flow">
        <div 
          v-for="(step, index) in steps" 
          :key="index"
          class="step" 
          :class="{ active: currentStep >= index + 1 }"
        >
          <div class="step-circle">{{ index + 1 }}</div>
          <div class="step-label">{{ step.label }}</div>
        </div>
      </div>

      <form>
        <!-- 节点一：初步接案与信息登记 -->
        <div class="form-section" :class="{ active: currentStep === 1 }" v-show="currentStep === 1">
          <h2 class="section-title">初步接案与信息登记</h2>

          <div class="form-group">
            <label for="service-channel" class="required">服务请求渠道</label>
            <select id="service-channel" class="form-input" v-model="form.step1.serviceChannel">
              <option value="">请选择</option>
              <option value="phone">电话</option>
              <option value="online">线上平台</option>
              <option value="referral">机构转介</option>
              <option value="other">其他</option>
            </select>
          </div>

          <div class="form-group">
            <label for="name" class="required">姓名</label>
            <input type="text" id="name" class="form-input" v-model="form.step1.name" placeholder="请输入服务对象姓名">
          </div>

          <div class="form-group">
            <label for="age" class="required">年龄</label>
            <input type="number" id="age" class="form-input" v-model.number="form.step1.age" placeholder="请输入年龄">
          </div>

          <div class="form-group">
            <label class="required">性别</label>
            <div class="radio-group">
              <div class="checkbox-item" :class="{ 'is-checked': form.step1.gender === 'male' }" @click="form.step1.gender = 'male'">
                <input type="radio" :checked="form.step1.gender === 'male'" name="gender" tabindex="-1" /> 男
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.step1.gender === 'female' }" @click="form.step1.gender = 'female'">
                <input type="radio" :checked="form.step1.gender === 'female'" name="gender" tabindex="-1" /> 女
              </div>
            </div>
          </div>

          <div class="form-group">
            <label for="contact" class="required">联系方式</label>
            <input type="tel" id="contact" class="form-input" v-model="form.step1.contact" placeholder="请输入手机号码">
          </div>

          <div class="form-group">
            <label for="health-needs" class="required">核心健康诉求</label>
            <textarea id="health-needs" class="form-input" v-model="form.step1.healthNeeds" rows="3" placeholder="请详细描述服务对象的健康诉求"></textarea>
          </div>

          <div class="btn-group">
            <button type="button" class="btn btn-prev" disabled>上一步</button>
            <button type="button" class="btn btn-next" @click="nextStep">下一步</button>
          </div>
        </div>

        <!-- 节点二：初步筛选 -->
        <div class="form-section" :class="{ active: currentStep === 2 }" v-show="currentStep === 2">
          <h2 class="section-title">初步筛选</h2>

          <div class="form-group">
            <label for="address" class="required">居住地址</label>
            <input type="text" id="address" class="form-input" v-model="form.step2.address" placeholder="请输入详细地址">
            <p class="input-hint">用于判断是否在服务覆盖区域内</p>
          </div>

          <div class="form-group">
            <label class="required">服务项目匹配度</label>
            <div class="checkbox-group">
              <div 
                v-for="service in serviceOptions" 
                :key="service.value"
                class="checkbox-item" 
                :class="{ 'is-checked': form.step2.serviceMatch.includes(service.value) }" 
                @click="toggleCheckbox(form.step2.serviceMatch, service.value)"
              >
                <input type="checkbox" :checked="form.step2.serviceMatch.includes(service.value)" @change.stop /> {{ service.label }}
              </div>
            </div>
          </div>

          <div class="form-group">
            <label class="required">是否存在明确的护理需求</label>
            <div class="radio-group">
              <div class="checkbox-item" :class="{ 'is-checked': form.step2.nursingNeed === 'yes' }" @click="form.step2.nursingNeed = 'yes'">
                <input type="radio" :checked="form.step2.nursingNeed === 'yes'" name="nursing-need" tabindex="-1" /> 是
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.step2.nursingNeed === 'no' }" @click="form.step2.nursingNeed = 'no'">
                <input type="radio" :checked="form.step2.nursingNeed === 'no'" name="nursing-need" tabindex="-1" /> 否
              </div>
            </div>
          </div>

          <div class="form-group">
            <label for="screening-notes">筛选备注</label>
            <textarea id="screening-notes" class="form-input" v-model="form.step2.screeningNotes" rows="3" placeholder="如有不符合条件的情况，请在此说明并提供其他资源建议"></textarea>
          </div>

          <div class="btn-group">
            <button type="button" class="btn btn-prev" @click="prevStep">上一步</button>
            <button type="button" class="btn btn-next" @click="nextStep">下一步</button>
          </div>
        </div>

        <!-- 节点三：高级实践护士初审 -->
        <div class="form-section" :class="{ active: currentStep === 3 }" v-show="currentStep === 3">
          <h2 class="section-title">高级实践护士初审</h2>

          <div class="form-group">
            <label class="required">需求复杂性评估</label>
            <div class="radio-group">
              <div class="checkbox-item" :class="{ 'is-checked': form.step3.complexity === 'low' }" @click="form.step3.complexity = 'low'">
                <input type="radio" :checked="form.step3.complexity === 'low'" name="complexity" tabindex="-1" /> 简单（单一健康问题）
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.step3.complexity === 'medium' }" @click="form.step3.complexity = 'medium'">
                <input type="radio" :checked="form.step3.complexity === 'medium'" name="complexity" tabindex="-1" /> 中等（多个健康问题）
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.step3.complexity === 'high' }" @click="form.step3.complexity = 'high'">
                <input type="radio" :checked="form.step3.complexity === 'high'" name="complexity" tabindex="-1" /> 复杂（疑难、多问题交织）
              </div>
            </div>
          </div>

          <div class="form-group">
            <label class="required">风险与收益评估</label>
            <div class="radio-group">
              <div class="checkbox-item" :class="{ 'is-checked': form.step3.benefitRisk === 'high-benefit' }" @click="form.step3.benefitRisk = 'high-benefit'">
                <input type="radio" :checked="form.step3.benefitRisk === 'high-benefit'" name="benefit-risk" tabindex="-1" /> 高收益，低风险
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.step3.benefitRisk === 'medium-benefit' }" @click="form.step3.benefitRisk = 'medium-benefit'">
                <input type="radio" :checked="form.step3.benefitRisk === 'medium-benefit'" name="benefit-risk" tabindex="-1" /> 中等收益，可控风险
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.step3.benefitRisk === 'low-benefit' }" @click="form.step3.benefitRisk = 'low-benefit'">
                <input type="radio" :checked="form.step3.benefitRisk === 'low-benefit'" name="benefit-risk" tabindex="-1" /> 低收益，高风险
              </div>
            </div>
          </div>

          <div class="form-group">
            <label class="required">服务能力匹配</label>
            <div class="radio-group">
              <div class="checkbox-item" :class="{ 'is-checked': form.step3.resourceMatch === 'yes' }" @click="form.step3.resourceMatch = 'yes'">
                <input type="radio" :checked="form.step3.resourceMatch === 'yes'" name="resource-match" tabindex="-1" /> 有相应资源与能力
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.step3.resourceMatch === 'partial' }" @click="form.step3.resourceMatch = 'partial'">
                <input type="radio" :checked="form.step3.resourceMatch === 'partial'" name="resource-match" tabindex="-1" /> 部分资源可匹配
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.step3.resourceMatch === 'no' }" @click="form.step3.resourceMatch = 'no'">
                <input type="radio" :checked="form.step3.resourceMatch === 'no'" name="resource-match" tabindex="-1" /> 无相应资源
              </div>
            </div>
          </div>

          <div class="form-group">
            <label for="nurse-assessment">护士评估意见</label>
            <textarea id="nurse-assessment" class="form-input" v-model="form.step3.nurseAssessment" rows="3" placeholder="请详细描述专业判断及建议"></textarea>
          </div>

          <div class="form-group">
            <label class="required">初审决定</label>
            <div class="radio-group">
              <div class="checkbox-item" :class="{ 'is-checked': form.step3.initialDecision === 'assess' }" @click="form.step3.initialDecision = 'assess'">
                <input type="radio" :checked="form.step3.initialDecision === 'assess'" name="initial-decision" tabindex="-1" /> 建议深入评估
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.step3.initialDecision === 'reject' }" @click="form.step3.initialDecision = 'reject'">
                <input type="radio" :checked="form.step3.initialDecision === 'reject'" name="initial-decision" tabindex="-1" /> 婉拒服务
              </div>
            </div>
          </div>

          <div class="btn-group">
            <button type="button" class="btn btn-prev" @click="prevStep">上一步</button>
            <button type="button" class="btn btn-next" @click="nextStep">下一步</button>
          </div>
        </div>

        <!-- 节点四：综合评估与需求判定 -->
        <div class="form-section" :class="{ active: currentStep === 4 }" v-show="currentStep === 4">
          <h2 class="section-title">综合评估与需求判定</h2>

          <div class="form-group">
            <label class="required">高级健康评估五维度模型</label>
            <div class="checkbox-group">
              <div 
                v-for="dimension in dimensionOptions" 
                :key="dimension.value"
                class="checkbox-item" 
                :class="{ 'is-checked': form.step4.assessmentDimensions.includes(dimension.value) }" 
                @click="toggleCheckbox(form.step4.assessmentDimensions, dimension.value)"
              >
                <input type="checkbox" :checked="form.step4.assessmentDimensions.includes(dimension.value)" @change.stop /> {{ dimension.label }}
              </div>
            </div>
          </div>

          <div class="form-group">
            <label for="health-problems">初步识别核心健康问题</label>
            <textarea id="health-problems" class="form-input" v-model="form.step4.healthProblems" rows="3" placeholder="请列出初步识别的核心健康问题"></textarea>
          </div>

          <div class="form-group">
            <label class="required">服务需求真实性与紧迫性</label>
            <div class="radio-group">
              <div class="checkbox-item" :class="{ 'is-checked': form.step4.urgency === 'high' }" @click="form.step4.urgency = 'high'">
                <input type="radio" :checked="form.step4.urgency === 'high'" name="urgency" tabindex="-1" /> 高紧迫性
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.step4.urgency === 'medium' }" @click="form.step4.urgency = 'medium'">
                <input type="radio" :checked="form.step4.urgency === 'medium'" name="urgency" tabindex="-1" /> 中等紧迫性
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.step4.urgency === 'low' }" @click="form.step4.urgency = 'low'">
                <input type="radio" :checked="form.step4.urgency === 'low'" name="urgency" tabindex="-1" /> 低紧迫性
              </div>
            </div>
          </div>

          <div class="form-group">
            <label class="required">是否符合高级实践护理个案标准</label>
            <div class="radio-group">
              <div class="checkbox-item" :class="{ 'is-checked': form.step4.meetStandard === 'yes' }" @click="form.step4.meetStandard = 'yes'">
                <input type="radio" :checked="form.step4.meetStandard === 'yes'" name="meet-standard" tabindex="-1" /> 符合
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.step4.meetStandard === 'no' }" @click="form.step4.meetStandard = 'no'">
                <input type="radio" :checked="form.step4.meetStandard === 'no'" name="meet-standard" tabindex="-1" /> 不符合
              </div>
            </div>
          </div>

          <div class="form-group">
            <label for="assessment-report">收案评估报告摘要</label>
            <textarea id="assessment-report" class="form-input" v-model="form.step4.assessmentReport" rows="3" placeholder="请简要描述评估结果"></textarea>
          </div>

          <div class="btn-group">
            <button type="button" class="btn btn-prev" @click="prevStep">上一步</button>
            <button type="button" class="btn btn-next" @click="nextStep">下一步</button>
          </div>
        </div>

        <!-- 节点五：签署服务协议与知情同意 -->
        <div class="form-section" :class="{ active: currentStep === 5 }" v-show="currentStep === 5">
          <h2 class="section-title">签署服务协议与知情同意</h2>

          <div class="document-preview">
            <h4>服务协议主要内容</h4>
            <p>• 服务内容与频次：详细说明提供的护理服务项目及服务频率</p>
            <p>• 收费标准：明确各项服务的收费标准及支付方式</p>
            <p>• 双方权利义务：明确服务提供方和接受方的权利与义务</p>
            <p>• 潜在风险：说明服务过程中可能存在的风险及应对措施</p>
          </div>

          <div class="document-preview">
            <h4>隐私保护政策</h4>
            <p>• 个人信息收集范围：明确收集的个人信息类型及用途</p>
            <p>• 信息保护措施：说明采取的信息安全保护措施</p>
            <p>• 信息使用限制：明确个人信息的使用范围及限制</p>
            <p>• 用户权利：说明用户对个人信息的查询、更正等权利</p>
          </div>

          <div class="form-group">
            <div class="checkbox-item" :class="{ 'is-checked': form.step5.agreeService }" @click="form.step5.agreeService = !form.step5.agreeService">
              <input type="checkbox" :checked="form.step5.agreeService" @change.stop /> 我已阅读并理解《服务协议》全部内容，同意接受协议条款
            </div>
          </div>

          <div class="form-group">
            <div class="checkbox-item" :class="{ 'is-checked': form.step5.agreePrivacy }" @click="form.step5.agreePrivacy = !form.step5.agreePrivacy">
              <input type="checkbox" :checked="form.step5.agreePrivacy" @change.stop /> 我已阅读并理解《隐私保护政策》全部内容，同意个人信息处理方式
            </div>
          </div>

          <div class="form-group">
            <div class="checkbox-item" :class="{ 'is-checked': form.step5.agreeInformed }" @click="form.step5.agreeInformed = !form.step5.agreeInformed">
              <input type="checkbox" :checked="form.step5.agreeInformed" @change.stop /> 我已充分了解服务内容、潜在风险及双方权利义务，自愿接受服务
            </div>
          </div>

          <div class="form-group">
            <label for="signature-name" class="required">签署人姓名</label>
            <input type="text" id="signature-name" class="form-input" v-model="form.step5.signatureName" placeholder="请输入签署人姓名">
          </div>

          <div class="form-group">
            <label for="signature-date" class="required">签署日期</label>
            <picker mode="date" :value="form.step5.signatureDate || getTodayStr()" @change="onSignaturePickerChange">
              <view class="form-input">{{ form.step5.signatureDate || '请选择签署日期' }}</view>
            </picker>
          </div>

          <div class="btn-group">
            <button type="button" class="btn btn-prev" @click="prevStep">上一步</button>
            <button type="button" class="btn btn-next" @click="nextStep">下一步</button>
          </div>
        </div>

        <!-- 节点六：正式立案并建立健康档案 -->
        <div class="form-section" :class="{ active: currentStep === 6 }" v-show="currentStep === 6">
          <h2 class="section-title">正式立案并建立健康档案</h2>

          <div class="form-group">
            <label for="case-manager" class="required">个案管理师</label>
            <input type="text" id="case-manager" class="form-input" v-model="form.step6.caseManager" placeholder="请输入负责的个案管理师姓名">
          </div>

          <div class="form-group">
            <label for="service-plan">初步服务计划</label>
            <textarea id="service-plan" class="form-input" v-model="form.step6.servicePlan" rows="3" placeholder="请简要描述初步制定的服务计划"></textarea>
          </div>

          <div class="form-group">
            <label class="required">档案创建状态</label>
            <div class="radio-group">
              <div class="checkbox-item" :class="{ 'is-checked': form.step6.recordStatus === 'created' }" @click="form.step6.recordStatus = 'created'">
                <input type="radio" :checked="form.step6.recordStatus === 'created'" name="record-status" tabindex="-1" /> 电子健康档案已创建
              </div>
              <div class="checkbox-item" :class="{ 'is-checked': form.step6.recordStatus === 'pending' }" @click="form.step6.recordStatus = 'pending'">
                <input type="radio" :checked="form.step6.recordStatus === 'pending'" name="record-status" tabindex="-1" /> 档案创建中
              </div>
            </div>
          </div>

          <div class="form-group">
            <div class="checkbox-item" :class="{ 'is-checked': form.confirmed }" @click="form.confirmed = !form.confirmed">
              <input type="checkbox" :checked="form.confirmed" @change.stop />
              确认信息无误，提交记录
            </div>
          </div>

          <div class="btn-group">
            <button type="button" class="btn btn-prev" @click="prevStep">上一步</button>
            <button type="submit" class="btn btn-submit" @click.prevent="onSubmit" :disabled="!form.confirmed">提交并完成收案</button>
          </div>
        </div>
      </form>
    </div>
  </CollapsibleSection>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, watch } from 'vue'
import CollapsibleSection from '@/components/CollapsibleSection.vue'
import Taro from '@tarojs/taro'

// 存储键名
const STORAGE_KEY = 'admissionFormData'

interface Props {
  isExpanded: boolean
}

interface Emits {
  (e: 'toggle'): void
}

defineProps<Props>()
defineEmits<Emits>()

// 流程步骤
const steps = [
  { label: '初步接案' },
  { label: '初步筛选' },
  { label: '护士初审' },
  { label: '综合评估' },
  { label: '签署协议' },
  { label: '正式立案' }
]

// 当前步骤
const currentStep = ref(1)

// 服务项目选项
const serviceOptions = [
  { label: '出院后延续护理', value: '出院后延续护理' },
  { label: '携带管路护理', value: '携带管路护理' },
  { label: '行动不便照护', value: '行动不便照护' },
  { label: '慢性病管理', value: '慢性病管理' },
  { label: '其他护理需求', value: '其他护理需求' }
]

// 评估维度选项
const dimensionOptions = [
  { label: '生理健康', value: '生理健康' },
  { label: '心理健康', value: '心理健康' },
  { label: '社会功能', value: '社会功能' },
  { label: '环境因素', value: '环境因素' },
  { label: '健康行为', value: '健康行为' }
]

// 表单数据
const form = reactive({
  step1: {
    serviceChannel: '',
    name: '',
    age: undefined as number | undefined,
    gender: '',
    contact: '',
    healthNeeds: ''
  },
  step2: {
    address: '',
    serviceMatch: [] as string[],
    nursingNeed: '',
    screeningNotes: ''
  },
  step3: {
    complexity: '',
    benefitRisk: '',
    resourceMatch: '',
    nurseAssessment: '',
    initialDecision: ''
  },
  step4: {
    assessmentDimensions: [] as string[],
    healthProblems: '',
    urgency: '',
    meetStandard: '',
    assessmentReport: ''
  },
  step5: {
    agreeService: false,
    agreePrivacy: false,
    agreeInformed: false,
    signatureName: '',
    signatureDate: ''
  },
  step6: {
    caseManager: '',
    servicePlan: '',
    recordStatus: ''
  },
  confirmed: false
})

// 获取当前日期字符串（格式：YYYY-MM-DD）
function getTodayString(): string {
  const today = new Date()
  const year = today.getFullYear()
  const month = String(today.getMonth() + 1).padStart(2, '0')
  const day = String(today.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// DatePicker visibility states
const signaturePickerVisible = ref(false)
const signatureTempDate = ref(getTodayStr())

// 获取当前日期（每次调用都重新计算，确保是当前日期）
function getTodayStr(): string {
  return getTodayString()
}

// 初始化默认日期为当前日期
form.step5.signatureDate = getTodayStr()

function openSignaturePicker() {
  // 如果没有日期或日期无效，设置为当前日期
  const currentDate = form.step5.signatureDate || getTodayStr()
  signatureTempDate.value = currentDate
  signaturePickerVisible.value = true
}

function onSignatureConfirm(val: any) {
  const dateStr = typeof val === 'string' 
    ? val 
    : Array.isArray(val) 
      ? `${val[0]}-${String(val[1]).padStart(2, '0')}-${String(val[2]).padStart(2, '0')}` 
      : String(val || '')
  
  if (dateStr) {
    form.step5.signatureDate = dateStr
    signatureTempDate.value = dateStr
    saveFormData()
  }
  signaturePickerVisible.value = false
}

function onSignaturePickerChange(e: any) {
  const v = e?.detail?.value ?? e?.target?.value ?? ''
  if (v) {
    form.step5.signatureDate = v
    saveFormData()
  }
}


// 处理复选框点击
function toggleCheckbox(array: string[], value: string) {
  const index = array.indexOf(value)
  if (index > -1) {
    array.splice(index, 1)
  } else {
    array.push(value)
  }
  // 自动保存
  saveFormData()
}

// 监听表单数据变化，自动保存
watch(() => form, () => {
  saveFormData()
}, { deep: true })

// 下一步
function nextStep() {
  if (currentStep.value < 6) {
    currentStep.value++
    saveFormData()
  }
}

// 上一步
function prevStep() {
  if (currentStep.value > 1) {
    currentStep.value--
    saveFormData()
  }
}

// 深拷贝函数
function deepClone<T>(obj: T): T {
  return JSON.parse(JSON.stringify(obj))
}

// 归一化各种日期值为 YYYY-MM-DD 字符串
function normalizeDate(val: any): string {
  if (!val) return getTodayStr()
  if (typeof val === 'string') return val
  if (val instanceof Date) {
    const y = val.getFullYear()
    const m = String(val.getMonth() + 1).padStart(2, '0')
    const d = String(val.getDate()).padStart(2, '0')
    return `${y}-${m}-${d}`
  }
  if (Array.isArray(val) && val.length >= 3) {
    const y = String(val[0])
    const m = String(val[1]).padStart(2, '0')
    const d = String(val[2]).padStart(2, '0')
    return `${y}-${m}-${d}`
  }
  if (typeof val === 'object') {
    if (val.year && val.month && val.day) {
      const y = String(val.year)
      const m = String(val.month).padStart(2, '0')
      const d = String(val.day).padStart(2, '0')
      return `${y}-${m}-${d}`
    }
    if (val.date) return normalizeDate(val.date)
    if (val.selectedValue) return normalizeDate(val.selectedValue)
  }
  return getTodayStr()
}

// 保存表单数据到缓存
function saveFormData() {
  try {
    const formDataCopy = deepClone(form)
    const dataToSave = {
      ...formDataCopy,
      currentStep: currentStep.value
    }
    Taro.setStorageSync(STORAGE_KEY, dataToSave)
    console.log('✅ 收案表单数据已保存到缓存')
  } catch (error: any) {
    console.error('❌ 保存表单数据失败:', error)
    Taro.showToast({
      title: '保存数据失败',
      icon: 'none',
      duration: 2000
    })
  }
}

// 从缓存读取表单数据
function loadFormData() {
  try {
    const savedData = Taro.getStorageSync(STORAGE_KEY)
    if (savedData) {
      const parsedData = typeof savedData === 'string' ? JSON.parse(savedData) : savedData
      if (parsedData && typeof parsedData === 'object') {
        // 恢复步骤数据
        if (parsedData.step1) Object.assign(form.step1, parsedData.step1)
        if (parsedData.step2) {
          Object.assign(form.step2, parsedData.step2)
          if (!Array.isArray(form.step2.serviceMatch)) form.step2.serviceMatch = []
        }
        if (parsedData.step3) Object.assign(form.step3, parsedData.step3)
        if (parsedData.step4) {
          Object.assign(form.step4, parsedData.step4)
          if (!Array.isArray(form.step4.assessmentDimensions)) form.step4.assessmentDimensions = []
        }
        if (parsedData.step5) {
          Object.assign(form.step5, parsedData.step5)
          // 如果日期为空或者是未来日期，设置为当前日期
          const todayStr = getTodayStr()
          form.step5.signatureDate = normalizeDate(form.step5.signatureDate)
          // 防止未来年份
          const dateYear = parseInt(String(form.step5.signatureDate).split('-')[0])
          const currentYear = new Date().getFullYear()
          if (!dateYear || dateYear > currentYear + 1) {
            form.step5.signatureDate = todayStr
          }
        } else {
          // 如果没有 step5 数据，初始化日期为当前日期
          form.step5.signatureDate = getTodayStr()
        }
        if (parsedData.step6) Object.assign(form.step6, parsedData.step6)
        if (parsedData.confirmed !== undefined) form.confirmed = parsedData.confirmed
        
        // 恢复当前步骤
        if (parsedData.currentStep !== undefined && parsedData.currentStep >= 1 && parsedData.currentStep <= 6) {
          currentStep.value = parsedData.currentStep
        }
        
        console.log('✅ 收案表单数据已从缓存加载')
      }
    }
  } catch (error: any) {
    console.error('❌ 加载表单数据失败:', error)
  }
}

// 组件挂载时加载缓存数据
onMounted(() => {
  loadFormData()
})

function onSubmit() {
  // 保存数据到缓存
  saveFormData()
  
  // 这里可替换为真实提交逻辑
  Taro.showToast({
    title: '收案记录提交成功！',
    icon: 'success',
    duration: 2000
  })
}
</script>

<style scoped>
.form-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  padding: 18px;
}
.tip { 
  text-align: center; 
  margin-bottom: 20px; 
  color: #666; 
  font-size: 20px; 
  line-height: 1.6; 
}

/* 流程步骤指示器 */
.process-flow {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30px;
  position: relative;
  padding: 0 10px;
}

.process-flow::before {
  content: '';
  position: absolute;
  top: 15px;
  left: 10px;
  right: 10px;
  height: 2px;
  background-color: #e0e0e0;
  z-index: 1;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  z-index: 2;
  flex: 1;
}

.step-circle {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #e0e0e0;
  color: #999;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  margin-bottom: 8px;
  transition: all 0.3s;
  font-weight: 600;
}

.step.active .step-circle {
  background-color: #2c80ff;
  color: white;
}

.step-label {
  font-size: 16px;
  color: #999;
  text-align: center;
  max-width: 120px;
}

.step.active .step-label {
  color: #2c80ff;
  font-weight: 600;
}

.form-section {
  display: none;
}

.form-section.active {
  display: block;
}

.section-title {
  font-size: 18px;
  color: #2c80ff;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
  font-weight: 600;
}

.form-group {
  margin-bottom: 24px;
}

label {
  display: block;
  margin-bottom: 12px;
  font-weight: 600;
  font-size: 20px;
  color: #333;
  line-height: 1.5;
}

.required::after {
  content: " *";
  color: #ff4757;
}

.input-hint {
  font-size: 16px;
  color: #888;
  margin-top: 6px;
  line-height: 1.5;
}

/* 所有输入框统一样式 */
.form-input,
input[type='text'],
input[type='number'],
input[type='tel'],
input[type='date'],
select,
textarea {
  width: 100%;
  padding: 22px 26px;
  border: 2px solid #d0d7de;
  border-radius: 12px;
  font-size: 24px !important;
  background-color: #f8f9fa !important;
  color: #333 !important;
  box-sizing: border-box;
  -webkit-appearance: none;
  appearance: none;
  line-height: 1.7;
  min-height: 64px;
  transition: all 0.3s ease;
  font-weight: 500;
  display: block;
}

.form-input:hover,
input:hover,
select:hover,
textarea:hover {
  border-color: #b0b7c0 !important;
  background-color: #f0f1f3 !important;
}

.form-input:focus,
input:focus,
select:focus,
textarea:focus {
  border-color: #2c80ff !important;
  background-color: #fff !important;
  outline: none;
  box-shadow: 0 0 0 4px rgba(44, 128, 255, 0.15) !important;
  transform: translateY(-1px);
}

textarea.form-input,
textarea {
  min-height: 150px;
  resize: vertical;
  font-family: inherit;
  font-size: 24px !important;
  line-height: 1.7;
  padding: 22px 26px;
  background-color: #f8f9fa !important;
  border: 2px solid #d0d7de;
  border-radius: 12px;
  transition: all 0.3s ease;
  font-weight: 500;
}

.checkbox-group,
.radio-group {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-top: 10px;
}

.checkbox-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 18px 16px;
  background: #f9f9f9;
  border-radius: 8px;
  min-height: 60px;
  font-size: 20px;
  transition: all 0.2s ease;
  border: 2px solid #e9ecef;
  cursor: pointer;
  position: relative;
}

.checkbox-item:active {
  background-color: #f0f0f0;
}

.checkbox-item:has(input:checked),
.checkbox-item.is-checked {
  background-color: #e7f3ff !important;
  border-color: #2c80ff !important;
  border-width: 2px !important;
  box-shadow: 0 2px 8px rgba(44, 128, 255, 0.15);
}

.checkbox-item input[type="checkbox"],
.checkbox-item input[type="radio"] {
  width: 24px;
  height: 24px;
  min-width: 24px;
  min-height: 24px;
  cursor: pointer;
  accent-color: #2c80ff;
  flex-shrink: 0;
  margin: 0;
  pointer-events: none;
}

.checkbox-item input[type="checkbox"]:checked,
.checkbox-item input[type="radio"]:checked {
  accent-color: #2c80ff;
}

.checkbox-item:has(input:checked),
.checkbox-item.is-checked {
  color: #2c80ff;
  font-weight: 600;
}

.document-preview {
  background-color: #f9f9f9;
  border: 1px solid #eaeaea;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
}

.document-preview h4 {
  margin-bottom: 10px;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.document-preview p {
  font-size: 16px;
  color: #666;
  margin-bottom: 8px;
  line-height: 1.6;
}

.btn-group {
  display: flex;
  justify-content: space-between;
  gap: 16px;
  margin-top: 30px;
}

.btn {
  padding: 18px 24px;
  border: none;
  border-radius: 8px;
  font-size: 20px;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 600;
  min-height: 60px;
  flex: 1;
}

.btn-prev {
  background-color: #f5f7fa;
  color: #666;
  border: 2px solid #ddd;
}

.btn-prev:active:not(:disabled) {
  background-color: #e9ecef;
}

.btn-prev:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-next {
  background-color: #2c80ff;
  color: white;
}

.btn-next:active:not(:disabled) {
  background-color: #1a6fe0;
}

.btn-submit {
  background-color: #00c853;
  color: white;
  width: 100%;
}

.btn-submit:active:not(:disabled) {
  background-color: #00a043;
}

.btn-submit:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>
